package com.jade.explorer.dirscan;

import java.io.File;

public class DirScanner {

	//------------------------------Private fields
	private String _dir = "";
	private Project _root;

	
	//------------------------------Private methods
	private void scan(String path, TreeParent top){
		File f = new File(path);
		for(int i = f.list().length -1; i >= 0; i--){
			if(f.listFiles()[i].isDirectory()){
				TreeParent ch = new TreeParent(f.list()[i], f.listFiles()[i].getPath());
				top.addChild(ch);
				scan(f.listFiles()[i].getPath(), ch);
			}
			if(f.listFiles()[i].isFile()){
				if (!isProjectFile(f.list()[i])){
					TreeObject to = new TreeObject(f.list()[i], f.listFiles()[i].getPath());
					top.addChild(to);
				}
			}
		}
	}
	
	private boolean isProjectFile(String name){
		if(name.toLowerCase().indexOf(".project") >= 0)
			return true;
		return false;
	}
	
	
	private String getDirName(String path){
		
		String ss = "";
		for(int i = path.length()-1; i >= 0; i--){
			ss += path.charAt(i);
		}
		
		String res = "";
		for(int i = ss.indexOf("\\")-1; i >= 0; i--){
			res += ss.charAt(i);
		}
		return res;
	}
	
	//------------------------------Constructors
	public DirScanner(String dir){
		
		_dir = dir;
		_root = new Project(getDirName(_dir), _dir);
		scan(_dir, _root);
	}
	
	//------------------------------Public methods
	/**
	 * This method returns structure of selected directory
	 * @return <code>TreeParent root</code>
	 */
	public Project getStructure(){
		return _root;
	}
	
	public void setDir(String dir){
		_dir = dir;
	}
	
	public String getDir(){
		return _dir;
	}
}

